package com.oystertech.sportcms.service.impl;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.oystertech.sportcms.common.util.SecurityUtils;
import com.oystertech.sportcms.converter.AthleteConverter;
import com.oystertech.sportcms.mapper.AthleteMapper;
import com.oystertech.sportcms.model.entity.Athlete;
import com.oystertech.sportcms.model.form.AthleteForm;
import com.oystertech.sportcms.service.AthleteService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.HashMap;

/**
 * 针对表【athlete(运动员表)】的数据库操作Service实现
 *
 * @author Oyster Cheung
 * @version 2023-09-05
 * @since 2023-10-23
 */
@Service
@RequiredArgsConstructor
public class AthleteServiceImpl extends ServiceImpl<AthleteMapper, Athlete>
		implements AthleteService {

	private final AthleteConverter athleteConverter;

	@Override
	public boolean updateAthlete(Long id, AthleteForm athleteForm) {
		// 如果要改证件号，先加密，再查有没在本队注册
		if (StrUtil.isNotBlank(athleteForm.getIdCard())) {
			Assert.notNull(athleteForm.getIdCardType(), "请选择证件类型");

			String idCardEnc=SecurityUtils.idCardEncrypt(athleteForm.getIdCardType(), athleteForm.getIdCard());
			athleteForm.setIdCardEnc(idCardEnc);

			long count = this.count(new LambdaQueryWrapper<Athlete>()
					.eq(Athlete::getTeamId, athleteForm.getTeamId())
					.eq(Athlete::getIdCardType, athleteForm.getIdCardType())
					.eq(Athlete::getIdCardEnc, idCardEnc)
					.ne(Athlete::getIdCardEnc, "/")
			);
			Assert.isTrue(count == 0, "证件号已在此队注册");
		}

		Athlete entity = athleteConverter.form2Entity(athleteForm);
		entity.setId(id);
		return this.updateById(entity);
	}

	@Override
	public boolean saveAthlete(AthleteForm athleteForm) {
		// 扩展字段的配置
		HashMap<String, Object> extraParam = new HashMap<>();

		// 证件号加密
		String idCardEnc = SecurityUtils.idCardEncrypt(athleteForm.getIdCardType(), athleteForm.getIdCard());

		// 检查同证件号是否已在本队注册
		long count = this.count(new LambdaQueryWrapper<Athlete>()
				.eq(Athlete::getTeamId, athleteForm.getTeamId())
				.eq(Athlete::getIdCardType, athleteForm.getIdCardType())
				.eq(Athlete::getIdCardEnc, idCardEnc)
				.ne(Athlete::getIdCardEnc, "/")
		);
		Assert.isTrue(count == 0, "证件号已在此队注册");

		// 转换
		Athlete entity = athleteConverter.form2Entity(athleteForm);

		// 有些空字段要手动设置值
		entity.setId(IdUtil.getSnowflake(RandomUtil.randomInt(10, 31)).nextId());
		entity.setExtraParam(JSONUtil.toJsonStr(extraParam));
		entity.setIdCardEnc(idCardEnc);

		return this.save(entity);
	}
}




